using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using Microsoft.Extensions.Logging;

namespace SeataNet.PerformanceTests
{
    /// <summary>
    /// 性能测试结果分析工具
    /// </summary>
    public class PerformanceTestAnalyzer
    {
        private readonly ILogger<PerformanceTestAnalyzer> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        public PerformanceTestAnalyzer(ILogger<PerformanceTestAnalyzer> logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 分析性能测试结果
        /// </summary>
        /// <param name="resultFilePath">结果文件路径</param>
        /// <param name="outputPath">输出路径</param>
        /// <returns>分析结果</returns>
        public async Task<PerformanceTestAnalysis> AnalyzeResultsAsync(string resultFilePath, string outputPath = null)
        {
            if (string.IsNullOrEmpty(resultFilePath))
            {
                throw new ArgumentException("结果文件路径不能为空", nameof(resultFilePath));
            }

            _logger.LogInformation($"开始分析性能测试结果: {resultFilePath}");

            // 读取测试结果
            var json = await File.ReadAllTextAsync(resultFilePath);
            var results = JsonSerializer.Deserialize<List<PerformanceTestResult>>(json);

            if (results == null || results.Count == 0)
            {
                throw new InvalidOperationException("测试结果为空");
            }

            // 分析结果
            var analysis = new PerformanceTestAnalysis
            {
                TestDate = File.GetCreationTime(resultFilePath),
                TotalTests = results.Count,
                OverallSuccessRate = results.Average(r => r.SuccessRate),
                OverallAverageThroughput = results.Average(r => r.Throughput),
                OverallAverageResponseTime = TimeSpan.FromMilliseconds(results.Average(r => r.AverageResponseTime))
            };

            // 按模式分组分析
            var atResults = results.Where(r => r.TestName.Contains("AT模式")).ToList();
            var tccResults = results.Where(r => r.TestName.Contains("TCC模式")).ToList();
            var sagaResults = results.Where(r => r.TestName.Contains("SAGA模式")).ToList();

            if (atResults.Any())
            {
                analysis.AtModeAnalysis = new ModeAnalysis
                {
                    ModeName = "AT模式",
                    AverageThroughput = atResults.Average(r => r.Throughput),
                    AverageResponseTime = TimeSpan.FromMilliseconds(atResults.Average(r => r.AverageResponseTime)),
                    AverageSuccessRate = atResults.Average(r => r.SuccessRate),
                    MinResponseTime = TimeSpan.FromMilliseconds(atResults.Min(r => r.MinResponseTime)),
                    MaxResponseTime = TimeSpan.FromMilliseconds(atResults.Max(r => r.MaxResponseTime)),
                    P95ResponseTime = TimeSpan.FromMilliseconds(atResults.Average(r => r.P95ResponseTime)),
                    P99ResponseTime = TimeSpan.FromMilliseconds(atResults.Average(r => r.P99ResponseTime))
                };
            }

            if (tccResults.Any())
            {
                analysis.TccModeAnalysis = new ModeAnalysis
                {
                    ModeName = "TCC模式",
                    AverageThroughput = tccResults.Average(r => r.Throughput),
                    AverageResponseTime = TimeSpan.FromMilliseconds(tccResults.Average(r => r.AverageResponseTime)),
                    AverageSuccessRate = tccResults.Average(r => r.SuccessRate),
                    MinResponseTime = TimeSpan.FromMilliseconds(tccResults.Min(r => r.MinResponseTime)),
                    MaxResponseTime = TimeSpan.FromMilliseconds(tccResults.Max(r => r.MaxResponseTime)),
                    P95ResponseTime = TimeSpan.FromMilliseconds(tccResults.Average(r => r.P95ResponseTime)),
                    P99ResponseTime = TimeSpan.FromMilliseconds(tccResults.Average(r => r.P99ResponseTime))
                };
            }

            if (sagaResults.Any())
            {
                analysis.SagaModeAnalysis = new ModeAnalysis
                {
                    ModeName = "SAGA模式",
                    AverageThroughput = sagaResults.Average(r => r.Throughput),
                    AverageResponseTime = TimeSpan.FromMilliseconds(sagaResults.Average(r => r.AverageResponseTime)),
                    AverageSuccessRate = sagaResults.Average(r => r.SuccessRate),
                    MinResponseTime = TimeSpan.FromMilliseconds(sagaResults.Min(r => r.MinResponseTime)),
                    MaxResponseTime = TimeSpan.FromMilliseconds(sagaResults.Max(r => r.MaxResponseTime)),
                    P95ResponseTime = TimeSpan.FromMilliseconds(sagaResults.Average(r => r.P95ResponseTime)),
                    P99ResponseTime = TimeSpan.FromMilliseconds(sagaResults.Average(r => r.P99ResponseTime))
                };
            }

            // 生成性能对比
            analysis.PerformanceComparison = GeneratePerformanceComparison(analysis);

            // 生成优化建议
            analysis.OptimizationSuggestions = GenerateOptimizationSuggestions(analysis);

            // 保存分析结果
            if (!string.IsNullOrEmpty(outputPath))
            {
                await SaveAnalysisAsync(analysis, outputPath);
            }

            _logger.LogInformation($"性能测试结果分析完成");
            return analysis;
        }

        /// <summary>
        /// 生成性能对比
        /// </summary>
        /// <param name="analysis">分析结果</param>
        /// <returns>性能对比</returns>
        private PerformanceComparison GeneratePerformanceComparison(PerformanceTestAnalysis analysis)
        {
            var comparison = new PerformanceComparison();

            // 吞吐量对比
            if (analysis.AtModeAnalysis != null && analysis.TccModeAnalysis != null)
            {
                comparison.AtVsTccThroughputRatio = analysis.AtModeAnalysis.AverageThroughput / analysis.TccModeAnalysis.AverageThroughput;
                comparison.AtVsTccResponseTimeRatio = analysis.AtModeAnalysis.AverageResponseTime.TotalMilliseconds / analysis.TccModeAnalysis.AverageResponseTime.TotalMilliseconds;
            }

            if (analysis.AtModeAnalysis != null && analysis.SagaModeAnalysis != null)
            {
                comparison.AtVsSagaThroughputRatio = analysis.AtModeAnalysis.AverageThroughput / analysis.SagaModeAnalysis.AverageThroughput;
                comparison.AtVsSagaResponseTimeRatio = analysis.AtModeAnalysis.AverageResponseTime.TotalMilliseconds / analysis.SagaModeAnalysis.AverageResponseTime.TotalMilliseconds;
            }

            if (analysis.TccModeAnalysis != null && analysis.SagaModeAnalysis != null)
            {
                comparison.TccVsSagaThroughputRatio = analysis.TccModeAnalysis.AverageThroughput / analysis.SagaModeAnalysis.AverageThroughput;
                comparison.TccVsSagaResponseTimeRatio = analysis.TccModeAnalysis.AverageResponseTime.TotalMilliseconds / analysis.SagaModeAnalysis.AverageResponseTime.TotalMilliseconds;
            }

            // 确定最佳性能模式
            var throughputs = new Dictionary<string, double>();
            if (analysis.AtModeAnalysis != null)
                throughputs["AT"] = analysis.AtModeAnalysis.AverageThroughput;
            if (analysis.TccModeAnalysis != null)
                throughputs["TCC"] = analysis.TccModeAnalysis.AverageThroughput;
            if (analysis.SagaModeAnalysis != null)
                throughputs["SAGA"] = analysis.SagaModeAnalysis.AverageThroughput;

            if (throughputs.Any())
            {
                comparison.BestThroughputMode = throughputs.OrderByDescending(kvp => kvp.Value).First().Key;
            }

            // 确定最低延迟模式
            var responseTimes = new Dictionary<string, double>();
            if (analysis.AtModeAnalysis != null)
                responseTimes["AT"] = analysis.AtModeAnalysis.AverageResponseTime.TotalMilliseconds;
            if (analysis.TccModeAnalysis != null)
                responseTimes["TCC"] = analysis.TccModeAnalysis.AverageResponseTime.TotalMilliseconds;
            if (analysis.SagaModeAnalysis != null)
                responseTimes["SAGA"] = analysis.SagaModeAnalysis.AverageResponseTime.TotalMilliseconds;

            if (responseTimes.Any())
            {
                comparison.LowestLatencyMode = responseTimes.OrderBy(kvp => kvp.Value).First().Key;
            }

            return comparison;
        }

        /// <summary>
        /// 生成优化建议
        /// </summary>
        /// <param name="analysis">分析结果</param>
        /// <returns>优化建议</returns>
        private List<OptimizationSuggestion> GenerateOptimizationSuggestions(PerformanceTestAnalysis analysis)
        {
            var suggestions = new List<OptimizationSuggestion>();

            // 整体性能建议
            if (analysis.OverallAverageResponseTime.TotalMilliseconds > 100)
            {
                suggestions.Add(new OptimizationSuggestion
                {
                    Category = "整体性能",
                    Description = "平均响应时间较高，建议优化网络通信和数据库访问",
                    Priority = "高",
                    Details = new List<string>
                    {
                        "考虑使用连接池优化数据库连接",
                        "优化SeataNet客户端与TC服务器的网络通信",
                        "考虑使用本地缓存减少数据库访问"
                    }
                });
            }

            if (analysis.OverallSuccessRate < 0.99)
            {
                suggestions.Add(new OptimizationSuggestion
                {
                    Category = "可靠性",
                    Description = "成功率较低，建议检查事务处理逻辑",
                    Priority = "高",
                    Details = new List<string>
                    {
                        "检查事务超时配置",
                        "检查重试机制配置",
                        "检查网络连接稳定性"
                    }
                });
            }

            // AT模式优化建议
            if (analysis.AtModeAnalysis != null)
            {
                if (analysis.AtModeAnalysis.AverageResponseTime.TotalMilliseconds > 50)
                {
                    suggestions.Add(new OptimizationSuggestion
                    {
                        Category = "AT模式",
                        Description = "AT模式响应时间较高",
                        Priority = "中",
                        Details = new List<string>
                        {
                            "优化undo_log表结构和索引",
                            "考虑减少事务锁的持有时间",
                            "优化数据源代理配置"
                        }
                    });
                }
            }

            // TCC模式优化建议
            if (analysis.TccModeAnalysis != null)
            {
                if (analysis.TccModeAnalysis.AverageResponseTime.TotalMilliseconds > 60)
                {
                    suggestions.Add(new OptimizationSuggestion
                    {
                        Category = "TCC模式",
                        Description = "TCC模式响应时间较高",
                        Priority = "中",
                        Details = new List<string>
                        {
                            "优化Try/Confirm/Cancel方法的实现",
                            "考虑使用异步处理提高并发性能",
                            "优化资源预留逻辑"
                        }
                    });
                }
            }

            // SAGA模式优化建议
            if (analysis.SagaModeAnalysis != null)
            {
                if (analysis.SagaModeAnalysis.AverageResponseTime.TotalMilliseconds > 100)
                {
                    suggestions.Add(new OptimizationSuggestion
                    {
                        Category = "SAGA模式",
                        Description = "SAGA模式响应时间较高",
                        Priority = "中",
                        Details = new List<string>
                        {
                            "优化Saga执行链的顺序和并行度",
                            "优化补偿操作的性能",
                            "考虑使用状态机模式优化复杂流程"
                        }
                    });
                }
            }

            return suggestions;
        }

        /// <summary>
        /// 保存分析结果
        /// </summary>
        /// <param name="analysis">分析结果</param>
        /// <param name="outputPath">输出路径</param>
        private async Task SaveAnalysisAsync(PerformanceTestAnalysis analysis, string outputPath)
        {
            var json = JsonSerializer.Serialize(analysis, new JsonSerializerOptions
            {
                WriteIndented = true
            });

            await File.WriteAllTextAsync(outputPath, json);
            _logger.LogInformation($"分析结果已保存到: {outputPath}");
        }

        /// <summary>
        /// 生成性能测试报告
        /// </summary>
        /// <param name="analysis">分析结果</param>
        /// <param name="outputPath">输出路径</param>
        public async Task GenerateReportAsync(PerformanceTestAnalysis analysis, string outputPath)
        {
            var report = new StringWriter();

            report.WriteLine("# SeataNet 性能测试报告");
            report.WriteLine();
            report.WriteLine($"测试日期: {analysis.TestDate:yyyy-MM-dd HH:mm:ss}");
            report.WriteLine($"总测试数: {analysis.TotalTests}");
            report.WriteLine($"整体成功率: {analysis.OverallSuccessRate:P2}");
            report.WriteLine($"整体平均吞吐量: {analysis.OverallAverageThroughput:F2} 请求/秒");
            report.WriteLine($"整体平均响应时间: {analysis.OverallAverageResponseTime.TotalMilliseconds:F2} 毫秒");
            report.WriteLine();

            // 模式性能对比
            report.WriteLine("## 模式性能对比");
            report.WriteLine();

            if (analysis.AtModeAnalysis != null)
            {
                report.WriteLine($"### {analysis.AtModeAnalysis.ModeName}");
                report.WriteLine($"- 平均吞吐量: {analysis.AtModeAnalysis.AverageThroughput:F2} 请求/秒");
                report.WriteLine($"- 平均响应时间: {analysis.AtModeAnalysis.AverageResponseTime.TotalMilliseconds:F2} 毫秒");
                report.WriteLine($"- 成功率: {analysis.AtModeAnalysis.AverageSuccessRate:P2}");
                report.WriteLine($"- P95响应时间: {analysis.AtModeAnalysis.P95ResponseTime.TotalMilliseconds:F2} 毫秒");
                report.WriteLine($"- P99响应时间: {analysis.AtModeAnalysis.P99ResponseTime.TotalMilliseconds:F2} 毫秒");
                report.WriteLine();
            }

            if (analysis.TccModeAnalysis != null)
            {
                report.WriteLine($"### {analysis.TccModeAnalysis.ModeName}");
                report.WriteLine($"- 平均吞吐量: {analysis.TccModeAnalysis.AverageThroughput:F2} 请求/秒");
                report.WriteLine($"- 平均响应时间: {analysis.TccModeAnalysis.AverageResponseTime.TotalMilliseconds:F2} 毫秒");
                report.WriteLine($"- 成功率: {analysis.TccModeAnalysis.AverageSuccessRate:P2}");
                report.WriteLine($"- P95响应时间: {analysis.TccModeAnalysis.P95ResponseTime.TotalMilliseconds:F2} 毫秒");
                report.WriteLine($"- P99响应时间: {analysis.TccModeAnalysis.P99ResponseTime.TotalMilliseconds:F2} 毫秒");
                report.WriteLine();
            }

            if (analysis.SagaModeAnalysis != null)
            {
                report.WriteLine($"### {analysis.SagaModeAnalysis.ModeName}");
                report.WriteLine($"- 平均吞吐量: {analysis.SagaModeAnalysis.AverageThroughput:F2} 请求/秒");
                report.WriteLine($"- 平均响应时间: {analysis.SagaModeAnalysis.AverageResponseTime.TotalMilliseconds:F2} 毫秒");
                report.WriteLine($"- 成功率: {analysis.SagaModeAnalysis.AverageSuccessRate:P2}");
                report.WriteLine($"- P95响应时间: {analysis.SagaModeAnalysis.P95ResponseTime.TotalMilliseconds:F2} 毫秒");
                report.WriteLine($"- P99响应时间: {analysis.SagaModeAnalysis.P99ResponseTime.TotalMilliseconds:F2} 毫秒");
                report.WriteLine();
            }

            // 性能对比结论
            report.WriteLine("## 性能对比结论");
            report.WriteLine();

            if (analysis.PerformanceComparison != null)
            {
                report.WriteLine($"- 最佳吞吐量模式: {analysis.PerformanceComparison.BestThroughputMode}");
                report.WriteLine($"- 最低延迟模式: {analysis.PerformanceComparison.LowestLatencyMode}");
                report.WriteLine();
            }

            // 优化建议
            report.WriteLine("## 优化建议");
            report.WriteLine();

            foreach (var suggestion in analysis.OptimizationSuggestions)
            {
                report.WriteLine($"### {suggestion.Category} (优先级: {suggestion.Priority})");
                report.WriteLine(suggestion.Description);
                report.WriteLine();

                foreach (var detail in suggestion.Details)
                {
                    report.WriteLine($"- {detail}");
                }
                report.WriteLine();
            }

            // 保存报告
            await File.WriteAllTextAsync(outputPath, report.ToString());
            _logger.LogInformation($"性能测试报告已生成: {outputPath}");
        }
    }

    /// <summary>
    /// 性能测试分析结果
    /// </summary>
    public class PerformanceTestAnalysis
    {
        public DateTime TestDate { get; set; }
        public int TotalTests { get; set; }
        public double OverallSuccessRate { get; set; }
        public double OverallAverageThroughput { get; set; }
        public TimeSpan OverallAverageResponseTime { get; set; }
        public ModeAnalysis AtModeAnalysis { get; set; }
        public ModeAnalysis TccModeAnalysis { get; set; }
        public ModeAnalysis SagaModeAnalysis { get; set; }
        public PerformanceComparison PerformanceComparison { get; set; }
        public List<OptimizationSuggestion> OptimizationSuggestions { get; set; } = new List<OptimizationSuggestion>();
    }

    /// <summary>
    /// 模式分析结果
    /// </summary>
    public class ModeAnalysis
    {
        public string ModeName { get; set; }
        public double AverageThroughput { get; set; }
        public TimeSpan AverageResponseTime { get; set; }
        public double AverageSuccessRate { get; set; }
        public TimeSpan MinResponseTime { get; set; }
        public TimeSpan MaxResponseTime { get; set; }
        public TimeSpan P95ResponseTime { get; set; }
        public TimeSpan P99ResponseTime { get; set; }
    }

    /// <summary>
    /// 性能对比
    /// </summary>
    public class PerformanceComparison
    {
        public double AtVsTccThroughputRatio { get; set; }
        public double AtVsTccResponseTimeRatio { get; set; }
        public double AtVsSagaThroughputRatio { get; set; }
        public double AtVsSagaResponseTimeRatio { get; set; }
        public double TccVsSagaThroughputRatio { get; set; }
        public double TccVsSagaResponseTimeRatio { get; set; }
        public string BestThroughputMode { get; set; }
        public string LowestLatencyMode { get; set; }
    }

    /// <summary>
    /// 优化建议
    /// </summary>
    public class OptimizationSuggestion
    {
        public string Category { get; set; }
        public string Description { get; set; }
        public string Priority { get; set; }
        public List<string> Details { get; set; } = new List<string>();
    }
}